<template>
  <div class="repair-report">
    <h1>维修报表生成</h1>
    
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="待处理" :value="0" />
            <el-option label="维修中" :value="1" />
            <el-option label="维修完成" :value="2" />
            <el-option label="已归档" :value="3" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="success" @click="exportReport">导出报表</el-button>
        </el-form-item> -->
      </el-form>
    </el-card>
    
    <!-- 报表数据 -->
    <el-card class="report-card">
      <el-table :data="reportData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="工单ID" width="100" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="description" label="故障描述" />
        <el-table-column prop="reportTime" label="报修时间" width="180" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="repairUserId" label="维修人员" width="120">
          <template #default="{ row }">
            {{ row.repairUserId ? getUserName(row.repairUserId) : '未分配' }}
          </template>
        </el-table-column>
        <el-table-column prop="assignTime" label="分配时间" width="180" />
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        @current-change="fetchData"
        layout="total, prev, pager, next, jumper"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { listRepairorder } from '@/api/repairorder'
import { getUser } from '@/api/user'
import RepairLayout from './RepairLayout.vue'

const loading = ref(false)
const reportData = ref([])
const total = ref(0)

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: '',
  dateRange: []
})

const statusMap = {
  0: { text: '待处理', type: 'warning' },
  1: { text: '维修中', type: 'primary' },
  2: { text: '维修完成', type: 'success' },
  3: { text: '已归档', type: 'info' }
}

const getStatusText = (status) => {
  return statusMap[status]?.text || '未知状态'
}

const getStatusType = (status) => {
  return statusMap[status]?.type || ''
}

const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...queryParams,
      beginTime: queryParams.dateRange[0],
      endTime: queryParams.dateRange[1]
    }
    const res = await listRepairorder(params)
    reportData.value = res
    total.value = res.total
    
    // 获取维修人员姓名
    const repairUserIds = res.map(item => item.repairUserId).filter(Boolean)
    if (repairUserIds.length > 0) {
      await fetchUserNames(repairUserIds)
    }
  } catch (error) {
    console.error('获取维修报表失败:', error)
    ElMessage.error('获取维修报表失败')
  } finally {
    loading.value = false
  }
}

const resetQuery = () => {
  queryParams.status = ''
  queryParams.dateRange = []
  fetchData()
}

const exportReport = () => {
  ElMessage.success('导出报表功能待实现')
}

const userMap = ref({})

const fetchUserNames = async (ids) => {
  try {
    const uniqueIds = [...new Set(ids)]
    await Promise.all(uniqueIds.map(async id => {
      if (!userMap.value[id]) {
        const res = await getUser(id)
        userMap.value[id] = res.data.nickName || res.data.userName
      }
    }))
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

const getUserName = (id) => {
  return userMap.value[id] || id
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.repair-report {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.report-card {
  margin-top: 20px;
}
</style>